package cn.dceast.former.controller;

import cn.dceast.common.data.RtnData;
import cn.dceast.common.utils.ExportInternalUtil;
import cn.dceast.former.model.EyeModelComment;
import cn.dceast.former.service.EyeModelCommentService;
import cn.dceast.former.service.EyeShowResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * Created by zhouxiaa on 2017-07-18.
 * 展示图形设置和结果设置
 * */
@Controller
@RequestMapping("/eyeShowResultController")
@Api(tags = {"eyeShowResultController"})
public class EyeShowResultController {
    public static final Logger logger = LoggerFactory.getLogger(EyeShowResultController.class);

    @Autowired
    private EyeShowResultService eyeShowResultService;

    /**
     * 获取数据清单

     * @return
     */
    @ApiOperation(value = "获取数据清单", notes = "获取数据清单")
    @RequestMapping(value = "/getDataList.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getDataList(@RequestParam Integer modelId,@RequestParam String tableName,HttpSession session){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("modelId", modelId);
        params.put("tableName", tableName);
        params.put("userid", session.getAttribute("userid"));
        eyeShowResultService.getDataList(params);
        return RtnData.ok("执行中");
    }
    /**
     * 执行算法的回调

     * @return
     */
    @ApiOperation(value = "执行算法的回调", notes = "执行算法的回调")
    @RequestMapping(value = "/getResult.do")
    @ResponseBody
    public RtnData getResult(String resPath,String userId,String resTable,String resCode){
        System.out.println(resPath);
        System.out.println(userId);
        System.out.println(resTable);
        System.out.println(resCode);
        //更新结果表的状态为执行完成
        Map params = new HashMap();
        params.put("tableName",resTable);
        params.put("state","2");//2表示完成状态
        eyeShowResultService.updateState(params);
        //可以去读结果数据了
        eyeShowResultService.getResult(resPath,Integer.valueOf(userId),resTable);
        return RtnData.ok("回调成功");
    }
    /**
     * 获取变量名称

     * @return
     */
    @ApiOperation(value = "获取变量名称", notes = "获取变量名称")
    @RequestMapping(value = "/getValue.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getValueList(@RequestParam String tableName){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tableName", tableName);
        List<Map> list =eyeShowResultService.getValueList(params);
        return RtnData.ok(list);
    }

    /**
     * 获取算法执行的状态

     * @return
     */
    @ApiOperation(value = "获取算法执行的状态", notes = "获取算法执行的状态")
    @RequestMapping(value = "/getState.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getState(@RequestParam String tableName){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tableName", tableName);
        params.put("limit", 10);
        List<Map> list =eyeShowResultService.getState(params);
        return RtnData.ok(list);
    }
    /**
     * 获取结果清单

     * @return
     */
    @ApiOperation(value = "获取结果清单", notes = "获取结果清单")
    @RequestMapping(value = "/getResultList.do", method = RequestMethod.GET)
    @ResponseBody
    public RtnData getResultList(@RequestParam String tableName){
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tableName", tableName);
        params.put("limit", 20);
        List<Map> list =eyeShowResultService.getState(params);
        return RtnData.ok(list);
    }
    /**
     * 导出清单
     */
    @ApiOperation(value = "数据清单导出", notes = "数据清单导出")
    @RequestMapping(value="/down/exportExcel.do", method=RequestMethod.GET)
    @ResponseBody
    public RtnData exportExcel(HttpServletResponse response, @RequestParam String tableName,
                               @RequestParam(required = true) String fileName) {
        try {
            String fileName1 = new String(fileName.getBytes("gb2312"), "iso8859-1") + ".xlsx";
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName1);
            response.setCharacterEncoding("utf-8");
        }catch (Exception e) {
            e.printStackTrace();
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("tableName", tableName);
        List<Map> returnList = new ArrayList<>();
        returnList = eyeShowResultService.getState(params);

        // 创建一个Excel文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建一个工作表
        XSSFSheet sheet = workbook.createSheet("sheet");
        ExportInternalUtil exportUtil = new ExportInternalUtil(workbook,sheet);
        XSSFCellStyle headOneStyle = exportUtil.getHeadByOneStyle();
        XSSFCellStyle bodyStyle = exportUtil.getBodyStyle();
        XSSFCellStyle headByTowStyle = exportUtil.getHeadByTowStyle();
        // 添加表头行
        XSSFRow hssfRow = sheet.createRow(0);
//        CellRangeAddress cra_1=new CellRangeAddress(0, 0, 0, 9);
//        sheet.addMergedRegion(cra_1);
//        row.setHeight((short)1000);
        // 设置单元格格式居中
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        if(returnList!=null && returnList.size()>0){
            Map titleObj= (Map) returnList.get(0);
            // 添加表头内容
            Set set=titleObj.entrySet();
            Iterator iterator=set.iterator();
            int i = 0;
            while(iterator.hasNext()){
                Map.Entry<String, Object> enter=(Map.Entry<String, Object>) iterator.next();
                XSSFCell headCell = hssfRow.createCell(i);
                headCell.setCellStyle(headOneStyle);
                headCell.setCellValue(enter.getValue().toString());
                headCell.setCellStyle(cellStyle);
                i++;
            }
            // 添加数据内容
            Set contentSet = null;
            Iterator contentIterator = null;
            Map headObj = null;
            for (int n = 1; n < returnList.size(); n++) {
                headObj = (Map) returnList.get(n);
                contentSet=headObj.entrySet();
                contentIterator =contentSet.iterator();
                hssfRow = sheet.createRow(n);
                // 创建单元格，并设置值
                int j = 0;
                while(contentIterator.hasNext()){
                    Map.Entry<String, Object> enter=(Map.Entry<String, Object>) contentIterator.next();
                    XSSFCell cell  = hssfRow.createCell(j);
                    cell.setCellStyle(bodyStyle);
                    cell.setCellValue(enter.getValue().toString());
                    cell.setCellStyle(cellStyle);
                    j++;
                }
            }
        }else{
            return RtnData.fail("暂时数据导出");
        }

        // 保存Excel文件
        try {
            workbook.write(outputStream);
            if(outputStream!=null) {
                outputStream.flush();
                outputStream.close();
            }
            return RtnData.ok("下载成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RtnData.fail("导出失败");
        }
    }
}
